package com.config;

import com.pojo.Permissions;
import com.pojo.Users;
import com.service.PermissionsService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    UserService userService;
    @Autowired
    PermissionsService permissionsService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = userService.findByUserName(username);
        List<Permissions> permissions = permissionsService.getPermissionsByUserId(users.getUserId());
        if (users == null) {
            return null;
        } else {
            List<GrantedAuthority> auths = new ArrayList<>();
            for (Permissions permission : permissions) {
                System.out.println("权限:" + permission.getPermissionName());
                auths.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList(permission.getPermissionName()));
            }
            return new User(users.getUserName(), new BCryptPasswordEncoder().encode(users.getUserPassword()), auths);
        }
    }
}
